package com.mid;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by Lxk on 2019/7/14.
 */

public class Solution116 {
    static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    };

    public Node connect(Node root) {
        if(root==null){
            return null;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        Node last = root;
        Node curNode = null;
        while(!queue.isEmpty()){
            Node cur = queue.poll();
            if(cur.left!=null){
                curNode = cur.left;
                queue.add(cur.left);
            }
            if(cur.right!=null){
                curNode = cur.right;
                queue.add(cur.right);
            }
            if(cur==last){
                last = curNode;
                LinkedList<Node> list = (LinkedList<Node>) queue;
                for(int i = 0;i < list.size()-1; i++){
                    list.get(i).next = list.get(i+1);
                }
            }
        }
        return root;
    }

}
